/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.dialog;

import cn.ac.nercis.pes.common.utils.ConvertUtils;
import cn.ac.nercis.pes.community.component.progress.LayerScoreProgressBar;
import cn.ac.nercis.pes.community.component.progress.RingProgressIndicator;
import cn.ac.nercis.pes.community.utils.LogUtils;
import cn.ac.nercis.pes.community.utils.SpringUtils;
import cn.ac.nercis.pes.model.dto.report.ScoreStatDTO;
import cn.ac.nercis.pes.service.document.StatisticService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 系统得分信息弹框控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class ScoreInfoController implements Initializable {

    private static String TOOL_SCORE_SHOW_FORMAT = "测评得分：%s分";

    @FXML
    private RingProgressIndicator indicator;
    @FXML
    private VBox layerScoreBox;

    private Button toolScoreBtn;
    private String currentSystemId;

    private final StatisticService statisticService;

    public ScoreInfoController(){
        statisticService = SpringUtils.getBean(StatisticService.class);
    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        this.resetControl();
        layerScoreBox.getChildren()
                .forEach(node-> node.managedProperty().bind(node.visibleProperty()));
    }

    public void initializeData(String systemId,Button toolScoreBtn){
        this.currentSystemId = systemId;
        this.toolScoreBtn = toolScoreBtn;
        this.refreshScore();
    }

    public void refreshScore(){
        LogUtils.info(log, "获取系统得分...");
        LogUtils.record(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.statisticService.getSystemScoreInfo(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshScore(res.getData());
                    }else{
                        this.resetControl();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取系统得分出错!", ex);
                    return null;
                });
    }

    private void refreshScore(ScoreStatDTO scoreStat){
        this.toolScoreBtn.setText(String.format(TOOL_SCORE_SHOW_FORMAT, ConvertUtils.scoreToString(scoreStat.getOverallScore())));
        this.indicator.setProgress(scoreStat.getOverallScore());
        this.layerScoreBox.getChildren()
                .forEach(ls->{
                    if(ls instanceof LayerScoreProgressBar bar){
                        var tScore = scoreStat.getLayerScores()
                                .stream()
                                .filter(lt-> StringUtils.equals(lt.getTargetName(),bar.getLayerName()))
                                .findFirst();
                        if(tScore.isPresent()){
                            bar.setLayerScore(tScore.get().getTargetScore());
                            bar.setEvalScore(tScore.get().getEvalScore());
                        }
                        bar.setVisible(tScore.isPresent());
                    }
                });
    }

    private void resetControl(){
        this.indicator.setProgress(0);
        layerScoreBox.getChildren()
                .forEach(node->{
                    if(node instanceof LayerScoreProgressBar bar){
                        bar.setEvalScore(0.0);
                        bar.setLayerScore(0f);
                    }
                });
    }
}